from django.shortcuts import render

# Create your views here.

from .models import *
from .ser import *
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from django.core.paginator import Paginator
import re
import random
from django.contrib.auth.hashers import make_password, check_password

# 发送短信
# 导入第三方方法包  封装的短信验证
from utils.comm import send_message, get_redis


class Text(APIView):
    def get(self, request):
        code = random.randint(100000, 999999)
        result = send_message('18595604641', code, 1)
        print(result)
        return Response('ok')


# 存入redis表中
import redis
from django_redis import get_redis_connection


class Test1(APIView):
    def get(self, request):
        conn = get_redis()
        # conn = redis.Redis(host='localhost',port=6379)
        # 字符串
        # conn = get_redis_connection()
        conn.set('username', 'zhangsan')
        name = conn.get('username')
        # print(name)
        return Response(name)

    # 图片验证码测试  进入8000/users/createCaptcha


from utils.captcha.captcha import captcha





# 注册接口
class Reg(APIView):
    def post(self, request):
        # 验证用户名
        name = request.data.get('username')
        # 验证用户名是否为空
        if not name:
            return Response({"code": 10010})
        # 验证用户名是否合法
        reg = re.match("\w{5,10}$", name)
        if not reg:
            return Response({"code": 10011})
        # 验证用户名唯一
        user = User.objects.filter(username=name).first()
        if user:
            return Response({"code": 10012})

        # 验证密码
        password = request.data.get("password")
        if not password:
            return Response({"code": 10016})
        sreg = re.match("\w{5,20}$", password)
        if not sreg:
            return Response({"code": 10017})
        # return Response({"code": 200})

        # 验证确认密码
        password1 = request.data.get("password1")
        if not password1:
            return Response({"code": 10020})
        msg = re.match("\w{5,20}$", password1)
        if not msg:
            return Response({"code": 10021})
        if password != password1:
            return Response({"code": 20022})

        # 验证手机号
        mobile = request.data.get("mobile")
        if not mobile:
            return Response({"code": 10013})
        mreg = re.match("^1[3-9]\d{9}$", mobile)
        if not mreg:
            return Response({"code": 10014})
        mobiles = User.objects.filter(mobile=mobile).first()
        if mobiles:
            return Response({"code": 10015})

        # 验证手机验证码是否正确 根据手机验证
        imgcode = request.data.get('imgcode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if code != imgcode:
            return Response({"code": 10016})

        # 判断是否同意协议
        agree = request.data.get('agree')
        if not agree:
            return Response({"code":10031})
#注册
class Re(APIView):
    # 注册

    def post(self,request):
        # 验证用户名
        name = request.data.get('username')
        # 验证用户名是否为空
        if not name:
            return Response({"code": 10010})
        # 验证用户名是否合法
        reg = re.match("\w{5,10}$", name)
        if not reg:
            return Response({"code": 10011})
        # 验证用户名唯一
        user = User.objects.filter(username=name).first()
        if user:
            return Response({"code": 10012})

        # 验证密码
        password = request.data.get("password")
        if not password:
            return Response({"code": 10016})
        sreg = re.match("\w{5,20}$", password)
        if not sreg:
            return Response({"code": 10017})
        # return Response({"code": 200})

        # 验证确认密码
        password1 = request.data.get("password1")
        if not password1:
            return Response({"code": 10020})
        msg = re.match("\w{5,20}$", password1)
        if not msg:
            return Response({"code": 10021})
        if password != password1:
            return Response({"code": 20022})

        # 验证手机号
        mobile = request.data.get("mobile")
        if not mobile:
            return Response({"code": 10013})
        mreg = re.match("^1[3-9]\d{9}$", mobile)
        if not mreg:
            return Response({"code": 10014})
        mobiles = User.objects.filter(mobile=mobile).first()
        if mobiles:
            return Response({"code": 10015})

        # 验证手机验证码是否正确 根据手机验证
        imgcode = request.data.get('imgcode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if code != imgcode:
            return Response({"code": 10016})

        # 判断是否同意协议
        agree = request.data.get('agree')
        if not agree:
            return Response({"code": 10031})
        request.data['password'] = make_password(request.data.get('password'))
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            # pyjwt生成token返回

            # from django.contrib.auth import login
            # id = request.session.get('id')
            # login(request,id)

            return Response({"code": 200})
        else:
            return Response({"code": 10017})

class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        uid = request.data.get('uid')
        imgcode = request.data.get('imgcode')
        conn = get_redis()
        imgcodes = conn.get(uid)
        # print(mobile)
        # print(uid)
        # print(imgcode)
        # print(imgcodes)

        if imgcodes:
            imgcodes = str(imgcodes,encoding='utf8')
            if imgcodes.lower() == imgcode.lower():
                code1 = random.randint(100000, 999999)
                res = send_message(mobile, code1, 1)
                code = 10010
                if res:
                    code = 200
                    # 发送验证码存入redis
                    conn = get_redis()
                    conn.setex(mobile, 60, code1)
                return Response({"code": code})
        return Response({'code':10031})
# 图片验证码
class CreateCaptcha(APIView):
    def get(self, request):
        uuid = request.GET.get("uuid")
        name, text, img = captcha.generate_captcha()
        # redis存储text 也就数3a3d
        conn = get_redis()
        conn.set(uuid,text)
        return HttpResponse(img, content_type='image/jpg')
# 登录
class Login(APIView):
    def post(self,request):
        name = request.data.get("username")
        print(name)
        if not name:
            return Response({"code:":10041})
        mreg = re.match("\w{5,10}$", name)
        if not mreg:
            return Response({"code":10042})


        pwd = request.data.get("password")
        if not pwd:
            return Response({"code":10043})

        preg = re.match('\w{5,20}$',pwd)
        if not preg:
            return Response({"code":10044})


        return Response({"code":200})

















# 新闻接口
class JournalismM(APIView):
    def post(self, request):
        datas = JournalismSer(data=request.data)
        if datas.is_valid():
            datas.save()
            return Response({"code": 200, "list": datas.data})
        else:
            print(datas.errors)
            return Response({"code": 10010})

    def get(self, request):
        datas = Journalism.objects.all()
        cpage = request.GET.get("cpage")

        p = Paginator(datas, 2)
        stu = p.page(cpage)
        ser = JournalismSer(stu, many=True)
        return Response({"code": 200, 'list': ser.data, 'tpage': p.num_pages})


class AdvertisingM(APIView):
    def post(self, request):
        datas = AdvertisingSer(data=request.data)
        print(request.data)
        # return Response({"code":200})
        if datas.is_valid():
            datas.save()
            return Response({"code": 200, 'list': datas.data})
        else:
            print(datas.errors)
            return Response({"code": 10010})

    def get(self, request):
        datas = Advertising.objects.all()
        cpage = request.GET.get('cpage')
        p = Paginator(datas, 2)
        su = p.page(cpage)
        ser = AdvertisingSer(su, many=True)
        return Response({"code": 200, 'list': ser.data, 'tpage': p.num_pages})
